<template>
  <div class="flight-search">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="出发城市">
          <el-select
            v-model="searchForm.departureCity"
            filterable
            placeholder="请选择出发城市"
          >
            <el-option
              v-for="city in cities"
              :key="city.value"
              :label="city.label"
              :value="city.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="目的城市">
          <el-select
            v-model="searchForm.arrivalCity"
            filterable
            placeholder="请选择目的城市"
          >
            <el-option
              v-for="city in cities"
              :key="city.value"
              :label="city.label"
              :value="city.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="出发日期">
          <el-date-picker
            v-model="searchForm.departureDate"
            type="date"
            placeholder="选择出发日期"
            :picker-options="pickerOptions"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="searchFlights">查询航班</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 航班列表 -->
    <el-card class="flight-list" v-if="flights.length > 0">
      <div slot="header" class="clearfix">
        <span>航班信息</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="handleSortPrice">
          {{ sortOrder === 'asc' ? '价格升序' : '价格降序' }}
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="flights"
        style="width: 100%"
      >
        <el-table-column prop="flightNumber" label="航班号" width="120" />
        <el-table-column prop="departureCity" label="出发城市" width="120" />
        <el-table-column prop="arrivalCity" label="到达城市" width="120" />
        <el-table-column prop="departureTime" label="出发时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.departureTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="arrivalTime" label="到达时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.arrivalTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="flightDuration" label="飞行时长" width="120" />
        <el-table-column prop="pilotName" label="机长" width="120" />
        <el-table-column prop="crewNames" label="乘务员" width="180" />
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleViewDetails(scope.row)"
            >
              查看详情
            </el-button>
            <el-button
              size="mini"
              type="success"
              @click="handleBookFlight(scope.row)"
            >
              预订
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 无数据提示 -->
    <el-empty v-else-if="!loading" description="暂无航班信息"></el-empty>
  </div>
</template>

<script>
import axios from 'axios'
import moment from 'moment'

export default {
  name: 'FlightSearch',
  data() {
    return {
      searchForm: {
        departureCity: '',
        arrivalCity: '',
        departureDate: ''
      },
      flights: [],
      loading: false,
      sortOrder: 'asc',
      cities: [
        { value: '北京', label: '北京' },
        { value: '上海', label: '上海' },
        { value: '广州', label: '广州' },
        { value: '深圳', label: '深圳' },
        { value: '成都', label: '成都' },
        { value: '杭州', label: '杭州' },
        { value: '西安', label: '西安' },
        { value: '重庆', label: '重庆' },
        { value: '南京', label: '南京' },
        { value: '武汉', label: '武汉' }
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      }
    }
  },
  methods: {
    async searchFlights() {
      if (!this.validateForm()) {
        return
      }

      this.loading = true
      try {
        const response = await axios.get('/flights', {
          params: {
            departureCity: this.searchForm.departureCity,
            arrivalCity: this.searchForm.arrivalCity,
            departureDate: moment(this.searchForm.departureDate).format('YYYY-MM-DD')
          }
        })
        if (response.data.code === 0) {
          this.flights = response.data.data
          if (this.flights.length === 0) {
            this.$message.info('未找到符合条件的航班')
          }
        } else {
          this.$message.error(response.data.msg || '查询失败')
        }
      } catch (error) {
        this.$message.error('网络错误，请稍后重试')
        console.error('Error fetching flights:', error)
      } finally {
        this.loading = false
      }
    },

    validateForm() {
      if (!this.searchForm.departureCity) {
        this.$message.warning('请选择出发城市')
        return false
      }
      if (!this.searchForm.arrivalCity) {
        this.$message.warning('请选择目的城市')
        return false
      }
      if (!this.searchForm.departureDate) {
        this.$message.warning('请选择出发日期')
        return false
      }
      if (this.searchForm.departureCity === this.searchForm.arrivalCity) {
        this.$message.warning('出发城市和目的城市不能相同')
        return false
      }
      return true
    },

    handleSortPrice() {
      this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc'
      this.flights.sort((a, b) => {
        return this.sortOrder === 'asc' 
          ? a.price - b.price 
          : b.price - a.price
      })
    },

    handleViewDetails(flight) {
      this.$router.push({
        name: 'FlightDetail',
        params: { id: flight.flightId }
      })
    },

    handleBookFlight(flight) {
      // 检查用户是否登录
      const userInfo = localStorage.getItem('userInfo')
      if (!userInfo) {
        this.$message.warning('请先登录后再预订航班')
        this.$router.push('/login')
        return
      }
      
      // 跳转到预订页面
      this.$router.push({
        name: 'FlightBooking',
        params: { id: flight.flightId }
      })
    },

    formatDateTime(datetime) {
      return moment(datetime).format('YYYY-MM-DD HH:mm')
    }
  }
}
</script>

<style scoped>
.flight-search {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.flight-list {
  margin-top: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}

.el-form-item {
  margin-bottom: 10px;
  margin-right: 10px;
}

.el-select {
  width: 160px;
}

.el-date-picker {
  width: 160px;
}
</style> 